package com.campus.schedule.timer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.campus.schedule.entity.Merchant;
import com.campus.schedule.service.MerchantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 商户推荐排序过期清理定时任务
 * </p>
 *
 * @author ZhaoYuJie
 * @since 2025-01-15
 */
@Slf4j
@Service
public class MerchantSeqExpireScheduleService {

    @Autowired
    private MerchantService merchantService;

    /**
     * 每日凌晨0点30分执行，清理过期的商户推荐排序
     */
    @Scheduled(cron = "0 30 0 * * ?")
    public void clearExpiredMerchantSeq() {
        log.info("开始执行商户推荐排序过期清理任务");
        
        try {
            LocalDate currentDate = LocalDate.now();
            
            // 查询需要清理的商户：seq_no > 0 且 seq_expire_date < 当前日期
            LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.gt(Merchant::getSeqNo, 0)
                       .lt(Merchant::getSeqExpireDate, currentDate);
            
            List<Merchant> expiredMerchants = merchantService.list(queryWrapper);
            
            if (expiredMerchants.isEmpty()) {
                log.info("没有需要清理的过期商户推荐排序");
                return;
            }
            
            log.info("发现 {} 个过期的商户推荐排序，开始清理", expiredMerchants.size());
            
            // 批量更新：将 seq_no 设置为 0，seq_expire_date 设置为 null
            LambdaUpdateWrapper<Merchant> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.gt(Merchant::getSeqNo, 0)
                        .lt(Merchant::getSeqExpireDate, currentDate)
                        .set(Merchant::getSeqNo, 0)
                        .set(Merchant::getSeqExpireDate, null);
            
            boolean updateResult = merchantService.update(updateWrapper);
            
            if (updateResult) {
                log.info("商户推荐排序过期清理任务执行成功，共清理 {} 个商户", expiredMerchants.size());
                
                // 记录被清理的商户信息
                for (Merchant merchant : expiredMerchants) {
                    log.info("清理商户推荐排序：商户ID={}, 商户名称={}, 原排序号={}, 过期日期={}", 
                            merchant.getId(), merchant.getName(), merchant.getSeqNo(), merchant.getSeqExpireDate());
                }
            } else {
                log.error("商户推荐排序过期清理任务执行失败");
            }
            
        } catch (Exception e) {
            log.error("商户推荐排序过期清理任务执行异常", e);
        }
    }
}